package com.fy.tt.util;

import java.io.File;
import java.io.RandomAccessFile;

public class GenerateParser {
    final static String grammarFilePath = "G:\\test3\\languageExecutor\\src\\com\\language\\parser\\Language.g4";
    final static String outputPath = "G:\\test3\\languageExecutor\\src\\com\\language\\parser";
    final static String antlrJar = "G:\\test3\\languageExecutor\\lib\\antlr-4.8-complete.jar";
    final static String cmdString = "java -jar "+antlrJar+" -visitor -no-listener -encoding UTF-8 "+grammarFilePath;

    public static void generatePaser() {
        try{
            //先清空之前的java文件
            File file = new File(outputPath);		//获取其file对象
            File[] fs = file.listFiles();	//遍历path下的文件和目录，放在File数组中
            for(File f:fs){					//遍历File[]数组
                if(!f.isDirectory())		//若非目录(即文件)，则打印
                {
                    if(f.getName().contains(".java")&&!f.getName().contains("My")){
                        System.out.println(f);
                        f.delete();
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        CmdExec.cmd(cmdString,outputPath);

        try{
            //在生成的java文件头生成对应package
//            String addPackageString="package com.language"+bandId+".parser;  \n";
            String addPackageString="package com.language.parser;  \n";
            File file = new File(outputPath);		//获取其file对象
            File[] fs = file.listFiles();	//遍历path下的文件和目录，放在File数组中
            for(File f:fs){					//遍历File[]数组
                if(!f.isDirectory())		//若非目录(即文件)，则打印
                {
                    if(f.getName().contains(".java")&&!f.getName().contains("My")){
                        System.out.println(f);
                        appendFileHeader(addPackageString.getBytes(),f.getPath());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private static void appendFileHeader(byte[] header,String srcPath) throws Exception{
        RandomAccessFile src = new RandomAccessFile(srcPath, "rw");
        int srcLength = (int)src.length() ;
        byte[] buff = new byte[srcLength];
        src.read(buff , 0, srcLength);
        src.seek(0);
        src.write(header);
        src.seek(header.length);
        src.write(buff);
        src.close();
    }
}

